<?php

class CouponsnModel extends BaseModel
{
	const TYPE_MSEND = 1;//满多少送多少
	const TYPE_MONEY = 2;//现金卷
	
	const MAX_LEAVE = 1000;
	
	private $sn_info = null;
	private $cou_info = null;
	
    var $table  = 'coupon_sn';
    var $prikey = 'id';
    var $_name  = 'couponsn';
    
    
    var $_relation = array(
    		'belongs_to_user' => array(
    				'model'         => 'member',
    				'type'          => BELONGS_TO,
    				'foreign_key'   => 'user_id',
    				'reverse'       => 'has_couponsn',
    		),
    		'belongs_to_coupon' => array(
    				'model'         => 'coupon',
    				'type'          => BELONGS_TO,
    				'foreign_key'   => 'user_id',
    				'reverse'       => 'has_couponsn',
    		),
    );
    
    
    /*
     * 检测某一个优惠码是否可以使用
     * @auth bzyy
     * 2015-6-4 15:24:44
     */
    public function snStatusOk($condition,$user_id=null)
    {
    	$param = array('conditions'=>$condition);
    	$info = $this->get($param);
    	
    	if(empty($info))
    	{
    		$this->_errors['coupon'] = "卷码不存在";
    		return false;
    	}
    	
    	if(empty($info['user_id']) || (!empty($user_id) && $info['user_id']!=$user_id) || $info['status'] != 1 || $info['use_time']>0)
    	{
    		$this->_errors['coupon'] = "此优惠卷不存在或已失效";
    		return false;
    	}
    	
    	$c_param = array('conditions'=>"coupon_id='{$info['coupon_id']}'");
    	$cou_m = &m('coupon');
    	$coupon = $cou_m->get($c_param);
    	//start use time
    	if(empty($coupon))
    	{
    		$this->_errors['coupon'] = "优惠券已不存在";
    		return false;
    	}
    	if($coupon['status'] != 1)
    	{
    		$this->_errors['coupon'] = "当前优惠券处于非正常状态，不能使用。";
    		return false;
    	}
    	
    	//时间
    	$time = time();
    	if($coupon['use_times_start'] >0 && $coupon['use_times_start']>$time)
    	{
    		$this->_errors['coupon'] = "该优惠券的使用时间还没有到，暂不能使用。";
    		return false;
    	}
    	if($coupon['use_times_end'] > 0 && $coupon['use_times_end']<$time)
    	{
    		$this->_errors['coupon'] = "现在已经超出了该优惠券的使用时间，不能使用了";
    		return false;
    	}
    	
    	$this->cou_info = $coupon;
    	//$this->sn_info = $info;
    	
    	return true;
    }
    
    
    /*
     * 消费使用一个优惠券
     * @auth bzyy
     * 2015-6-4 16:05:34
     */
    public function consumeSn($condition,$user_id,$addon=array())
    {
    	//检测是否可用和有效
    	$flag = $this->snStatusOk($condition,$user_id);
    	if(!$flag)
    	{
    		return false;
    	}
    	//更新状态
    	$edit_data = array();
    	$edit_data['use_time'] = time();
    	$edit_data['status'] = 2;
    	$edit_data = array_merge($addon,$edit_data);
    	$flag = $this->edit($condition, $edit_data);
    	if($flag)//更新数量优惠券数量
    	{
    		$info = $this->get(array('conditions'=>$condition));
    		$cou_m = &m('coupon');
    		$sql = "update ". $cou_m ->table ." set usednum=usednum+1 where coupon_id = '{$info['coupon_id']}' limit 1 ";
    		return $cou_m->query($sql);
    	}
    	
    	return true;
    	
    }
    
    /*
     * 查询我所有拥有的，并且可用使用的优惠券码
     * @auth bzyy
     * 2015-6-4 16:49:37
     */
    public function mysn($user_id)
    {
    	$cou_m = &m('coupon');
    	$sn_m = &m('couponsn');
    	
    	$now = time();
    	
    	$sql = "select sn.id,sn.coupon_sn,cou.coupon_name,cou.coupon_value from {$sn_m->table} as sn left join {$cou_m->table} as cou on sn.coupon_id=cou.coupon_id ";
    	$where = " where sn.user_id='{$user_id}' and sn.status=1 and sn.use_time=0 ";
    	$where .= " and cou.status=1 and (cou.use_times_start = 0 or cou.use_times_start<{$now})  and (cou.use_times_end=0 or cou.use_times_end>{$now}) ";
    	
    	$order = " order by sn.id desc ";
    	
    	$data = $sn_m->getAll($sql.$where.$order);
    	
    	return $data;
    	
    }
    
    /*
     * 生成优惠券号码
     * @auth bzyy
     * 2015-6-5 12:03:47
     *  
     * 编号规则
	 * 00 1506021440 	002 	000006		x
	 * 类型      日期编号	              优惠券     	id自增数		校验位(优惠券+随机%10)
	 * 
	 * 01 表示第一种的类型，满x送y
     */
    public function makeSn($upid,$number=1,$pre='01')
    {
    	$sn = array();
    	//取得总数,初始化起始增量
    	$sql = "select count(*) as c from ".$this->table;
    	$c = $this->getOne($sql);
    	
    	
    	for($i=1;$i<=$number;$i++){
    		$sn[] = $c+$i;
    	}
    	
    	//组装号码
    	$now_str = $this->now_str?$this->now_str:date('ymdHi');
    	$num_c = substr(str_pad($upid, 3,'0',STR_PAD_LEFT),-3);
    	$nsn = array();
    	$r = rand(10, 1000);
    	foreach($sn as $k=>$v){
    		$x = ($v + $r)%10;
    		$code = $pre.$now_str. $num_c . substr(str_pad($v, 6,'0',STR_PAD_LEFT),-6).$x;
    		$nsn[] = $code;
    	}
    	
    	//查询号码
    	if($this->snUniqid($nsn))
    	{
    		return $nsn;
    	}
    	
    	return $this->makeSn($upid,$number,$pre);
    }
    
    /*
     * 实际的生成处理
     * 当前可以简化处理
     * @auth bzyy
     * 2015-6-5 12:33:51
     */
    public function createSn($up_id,$store_id,$num=1,$pre='01')
    {
    	$model = &m('coupon');
    	$params = array('conditions'=>"coupon_id={$up_id}");
    	$info = $model->get($params);
    	if(empty($info))
    	{
    		$this->_errors['error'] = "优惠券不存在";
    		return false;
    	}
    	if($info['status']!=1)
    	{
    		$this->_errors['error'] = "优惠券处于非正常状态，不可以生成优惠码";
    		return false;
    	}
    	
    	if($info['store_id']!= $store_id || $store_id==0)
    	{
    		$this->_errors['error'] = '您无权处理此优惠卷';
    		return false;
    	}
    	
    	//看未分配的数量有多少1000
    	$sql = "select count(*) as c from ".$this->table." where coupon_id={$up_id} and user_id=0";
    	$c = $this->getOne($sql);
    	if($c>=self::MAX_LEAVE)
    	{
    		$this->_errors['error'] = "当前未领取的优惠码达到". self::MAX_LEAVE ."条，不可以再次添加了";
    		return false;
    	}
    	
    	$les = self::MAX_LEAVE - $c;
    	if($les<$num)
    	{
    		$this->_errors['error'] = "由于未领取的优惠码，当前最多只能添加{$les}个优惠码";
    		return false;
    	}
    	
    	//准备生成
    	$sn = $this->makeSn($up_id,$num,$pre);
    	$time = time();
    	$addata = array();
    	foreach ($sn as $v)
    	{
    		$temp = array();
    		$temp['coupon_id'] = $up_id;
    		$temp['coupon_sn'] = $v;
    		
    		$temp['c_time'] = $time;
    		$addata[] = $temp;
    		
    	}
    	
    	$this->begin();
    	foreach ($addata as $val)
    	{
    		$f = $this->add($val);
    		if(!$f){
    			$this->rollback();
    			$this->_errors['error'] = '插入数据库时出错，请稍后再试';
    			return false;
    			break;
    		}
    	}
    	
    	$this->commit();
    	return true;
    	
    }
    
    /*
     * 检测某个优惠券是否在店中可以消费
     * @auth bzyy
     * 2015-6-8 10:19:26
     * $sn_cond @找到优惠券信息的条件
     */
    public function CanUserStroeSn($sn_cond,$uid,$stroe_id=0)
    {
    	$f = $this->snStatusOk($sn_cond,$uid);
    	if(!$f)
    	{
    		return false;
    	}
    	
    	if($this->cou_info['store_id']>0)//进行检测
    	{
    		if($stroe_id != $this->cou_info['store_id'])
    		{
    			$this->_errors['error'] = '此优惠券不能在该店铺中使用';
    			return false;
    		}
    	}
    	
    	return $this->cou_info;
    }
    
    /*
     * 检测是否存在重复的编号
     * @auth bzyy
     * 2015-6-5 12:12:08
     */
    protected function snUniqid($data)
    {
    	$sql = "select count(*) as c from ".$this->table;
    	$where = " where coupon_sn in (". implode(',', $data) .") ";
    	$c = $this->getOne($sql.$where);
    	
    	return $c==0;
    }
    
    /*
     * 给某个优惠券进行指定操作
     * @auth bzyy
     * 2015-6-9 17:39:48
     * 店家指定给用户
     * 店铺id
     */
    public function pointUser($conditon,$uid,$store_id)
    {
    	//找到优惠码
		$sn = $this->get(array('conditions'=>$conditon));
		
		if(empty($sn))
		{
			$this->_errors['error'] = '优惠码不存在';
			return false;
		}
		if($sn['status'] != 1)
		{
			$this->_errors['error'] = '优惠码处于非正常状态，不能指定用户';
			return false;
		}
		if($sn['user_id'] != 0)
		{
			$this->_errors['error'] = '该优惠码已被领取';
			return false;
		}

    	//找到优惠信息
    	$model = &m('coupon');
    	$cou = $model->get(array('conditions'=>"coupon_id='{$sn['coupon_id']}'"));
    	
    	if($cou['store_id'] != $store_id)
    	{
    		$this->_errors['error'] = '此店铺无权管理该优惠券';
    		return false;
    	}
    	
    	if(empty($cou) || $cou['status'] != 1)
    	{
    		$this->_errors['error'] = '该优惠卷不存在或处于非正常状态';
    		return false;
    	}
    	
    	//更新与插入的处理
    	$edit_data = array('user_id'=>$uid,'get_time'=>time());
    	$this->edit($sn['id'], $edit_data);
    	
    	return true;
    }
    
    
    /*
     * 用户自己领取某个优惠券
     * @auth bzyy
     * 2015-6-10 10:06:24
     *
     *
     */
    public function getsn($user_id,$cp_id,$stroe_id=0)
    {
    	//检测我是否存在未消费的
    	$param = array('conditions'=>"user_id='{$user_id}' and coupon_id='{$cp_id}' and use_time=0 ");
    	$sn = $this->get($param);
    	if(!empty($sn))
    	{
    		$this->_errors['error'] = "当前存在未消费的优惠券，不能领取";
    		return false;
    	}
    	
    	//看优惠券
    	$model = &m('coupon');
    	$cou = $model->get(array('conditions'=>"coupon_id='{$cp_id}'"));
    	
    	if(empty($cou))
    	{
    		$this->_errors['error'] = "对应优惠券不存在";
    		return false;
    	}
    	
    	if($cou['store_id']>0 && $cou['store_id'] != $stroe_id)
    	{
    		$this->_errors['error'] = "对应店铺无此优惠券";
    		return false;
    	}
    	
    	if($cou['status'] != 1)
    	{
    		$this->_errors['error'] = '优惠券处于非正常状态，不能领取';
    		return false;
    	}
    	
    	$time = time();
    	if($cou['start_time'] > 0 && $cou['start_time']>$time)
    	{
    		$this->_errors['error'] = '还未到领取时间';
    		return false;
    	}
    	if($cou['end_time'] >0 && $cou['end_time'] < $time)
    	{
    		$this->_errors['error'] = '已经超过了领取时间';
    		return false;
    	}
    	
    	//找一个优惠码
    	$sql = "update ".$this->table . " set user_id='{$user_id}',get_time='{$time}' where coupon_id='{$cp_id}' and user_id='0' and status=1 limit 1 ";
    	$f = $this->query($sql);
    	if(!$f)
    	{
    		$this->_errors['error'] = "优惠码已发放完了";
    		return false;
    	}
    	
    	//统计下发次数
    	$sql = " update ".$model->table . " set sendnum=sendnum+1 where coupon_id='{$cp_id}' limit 1";
    	$model->query($sql);
    	
    	return true;
    }
    
    
    
    
}

?>
